<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class ProductSku extends Model
{
    protected $casts = [
        'attrs' => 'array',
        'price' => 'array',
    ];

    protected $fillable = [
        'product_id',
        'price',
        'stock',
    ];

    protected $with = ["product", "cover"];

    public function getAttrsAttribute()
    {
        return $this->attr->pluck('id')->toArray();
    }

    public function getHashKeyAttribute()
    {
        return skuHashKey($this->attr->pluck('id')->toArray());
    }

    public function getDescriptionAttribute()
    {
        return $this->attr->pluck('attribute_value')->toArray();
    }

    public function cover()
    {
        return $this->hasOne(Image::class, 'type_id')
            ->where('type', Image::SKU_COVER)
            ->withDefault([
                'type' => Image::SKU_COVER,
            ]);
    }

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function attr()
    {
        return $this->belongsToMany(
            ProductSkuAttribute::class,
            'sku_attributes',
            'sku_id',
            'sku_attribute_id'
        );
    }

    // 减少库存
    public function decreaseStock($amount)
    {
        if ($amount < 0) {
            return false;
        }

        return $this->newQuery()
            ->where('id', $this->id)
            ->where('stock', '>=', $amount)
            ->decrement('stock', $amount);
    }

    // 添加库存
    public function addStock($amount)
    {
        if ($amount < 0) {
            return false;
        }
        $this->increment('stock', $amount);
    }
}
